package com.jadefashion.service;

import com.jadefashion.RedisUtils.RedisCache;
import com.jadefashion.pojo.Permission;
import com.jadefashion.pojo.Role;
import com.jadefashion.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component("springSecurityUserServiceImpl")
public class SpringSecurityUserServiceImpl implements UserDetailsService {
    @Autowired
    private RedisCache redisCache;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = redisCache.redisCache(username);
        System.out.println(user);
        Set<Role> roles = user.getRoles();//获取所有的角色
        List<GrantedAuthority> list=new ArrayList<>();
        for (Role role : roles) {//遍历角色，获得每个角色对应的权限集合
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {//遍历权限集合，获得所有权限，将其添加到list
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        UserDetails userDetails=new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return userDetails;
    }
}
